//
//  Main4ViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/8/31.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "Main4ViewController.h"
#import "GrabOrderTableViewCell.h"

#import "MJRefresh.h"
#import "UIColor+Hex.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "UserDefaultUtil.h"
#import "OrderDetailViewController.h"
#import "NoticeViewController.h"
@interface Main4ViewController ()

@property NSMutableArray *orderData;
@property int page;

@property NSString *startDate;
@property NSString *endDate;
@end

@implementation Main4ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _startDate = @"1970-01-01";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    _endDate = [formatter stringFromDate:[NSDate date]];
    
    
    self.tabview.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];

    
    self.tabview.delegate = self;
    self.tabview.dataSource = self;
    
    UINib *nib = [UINib nibWithNibName:@"GrabOrderTableViewCell" bundle:nil];
    [self.tabview registerNib:nib forCellReuseIdentifier:@"grab_order_cell"];
    
    
    //self.tabview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,0)];
    
    if ([self.tabview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tabview setSeparatorInset:UIEdgeInsetsZero];
    }
    self.tabview.separatorStyle = UITableViewCellSeparatorStyleNone;
    //self.tabview.contentInset = UIEdgeInsetsMake(4, 0, 0, 0);
    //self.tabview.scrollIndicatorInsets = UIEdgeInsetsMake(4, 0, 0, 0);
    
     __unsafe_unretained UITableView *tableView = self.tabview;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新数据");
        _page = 1;
        [self getData];
        
        [tableView.mj_header endRefreshing];

    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"加载更多");

        [self getData];
        [tableView.mj_footer endRefreshing];

    }];
    // 马上进入刷新状态
    [tableView.mj_header beginRefreshing];
    
    //头部图片
    self.topView.image = [UIImage imageNamed:@"grab_order_top" ];
    self.topView.contentMode = UIViewContentModeCenter;
    //self.edgesForExtendedLayout = UIRectEdgeNone;
    
   
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _orderData.count;
}
//item
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GrabOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"grab_order_cell"];
    
    NSDictionary *dic = self.orderData[indexPath.row];
    
    //订单来源
    if([dic[@"orderFrom"] isEqualToString:@"天猫"]){
        cell.order_from_image.image = [UIImage imageNamed:@"grab_order_tm"];
    }
    if([dic[@"orderFrom"] isEqualToString:@"4PL-天猫"]){
        cell.order_from_image.image = [UIImage imageNamed:@"grab_order_tm"];
    }
    if([dic[@"orderFrom"] isEqualToString:@"其它"]){
        cell.order_from_image.image = [UIImage imageNamed:@"grab_order_qt"];
    }
    if([dic[@"orderFrom"] isEqualToString:@"极有家"]){
        cell.order_from_image.image = [UIImage imageNamed:@"grab_order_jyj"];
    }
    if([dic[@"orderFrom"] isEqualToString:@"京东"]){
        cell.order_from_image.image = [UIImage imageNamed:@"order_order_from_jd"];
    }
    //订单号
    cell.order_no_text.text = dic[@"serviceNo"];
    

    
    //工单日期
    NSDateFormatter *sf = [[NSDateFormatter alloc]init];
    [sf setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDateFormatter *sf2 = [[NSDateFormatter alloc]init];
    [sf2 setDateFormat:@"yyyy-MM-dd"];
    NSDate * date = [sf dateFromString:dic[@"serviceDate"]];
    
    cell.order_date_text.text = [sf2 stringFromDate:date];
    //用户
    cell.order_user_text.text = [NSString stringWithFormat:@"%@(%@)",dic[@"userName"],dic[@"userPhone"]];
    //地址1
    cell.address1_text.text = [NSString stringWithFormat:@"提货:%@",dic[@"pickupAddress"]];
    //地址2
    cell.address2_text.text = [NSString stringWithFormat:@"上门:%@",dic[@"userAddress"]];

    cell.price_lab.text = [NSString stringWithFormat:@"%@元",dic[@"price"]];
    


    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 170.0;
}
-(void)viewDidLayoutSubviews
{
    if ([self.tabview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tabview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tabview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tabview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
//侧滑按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

{
    NSDictionary *dic = self.orderData[indexPath.row];

    UITableViewRowAction *grabRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"抢单" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [self sendData:dic[@"serviceNo"]];
    }];
    grabRowAction.backgroundColor = [UIColor colorWithHexString:@"#ff7e00"];
    UITableViewRowAction *phoneRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"电话" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        UIWebView*callWebview =[[UIWebView alloc] init];
        NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",dic[@"userPhone"]]];// 貌似tel:// 或者 tel: 都行
        [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
        //记得添加到view上
        [self.view addSubview:callWebview];
    }];
    
    return @[phoneRowAction,grabRowAction];
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


//点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
//    
//    NSDictionary *dic = self.orderData[indexPath.row];
//    
//    OrderDetailViewController *order = [story instantiateViewControllerWithIdentifier:@"order_detail"];
//    order.serviceNo = dic[@"serviceNo"];
//    [self.navigationController pushViewController:order animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)viewWillAppear:(BOOL)animated{
    _page = 1;
    [self getData];
    [super viewDidAppear:animated];
}

-(void) getData{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":[NSString stringWithFormat:@"%i",_page],@"size":[NSString stringWithFormat:@"%@",@"20"],@"startDate":_startDate,@"endDate":_endDate};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"query_Grab_Order" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            _page++;
            NSString *content = data[@"result"];
            
            NSLog(@"%@",content);
            NSArray *orderd = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (_page == 2) {
                self.orderData = [[NSMutableArray alloc]init];
                [self.orderData addObjectsFromArray:orderd];
            }else{
                [self.orderData addObjectsFromArray:orderd];
            }
            
            
            [self.tabview reloadData];
            
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        [MBProgressHUD hideHUD];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

-(void) sendData:(NSString *) serviceNo{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"serviceNo":serviceNo};
    
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"order_grab_operator" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
     [MBProgressHUD showMessage:@"抢单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        [MBProgressHUD hideHUD];
        
        if ([data[@"success"] boolValue]) {
            
            [MBProgressHUD showSuccess:@"抢单成功"];
            
            _page = 1;
            [self getData];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
- (IBAction)notice_click:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    NoticeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"notice_view"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)code_click:(id)sender {
    
    NSLog(@"启动二维码");
    
    static QRCodeReaderViewController *reader = nil;
    static dispatch_once_t onceToken;
    
    
    dispatch_once(&onceToken, ^{
        reader                        = [QRCodeReaderViewController new];
        reader.modalPresentationStyle = UIModalPresentationFormSheet;
    });
    reader.delegate = self;
    
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        
    }];
    
    [self presentViewController:reader animated:YES completion:NULL];
}
//二维码回调
- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result{
    
    NSLog(@"%@",result);
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    NSDictionary * data = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    [self getServiceNo:data[@"serviceNo"]];
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader{
    NSLog(@"readerDidCancel被执行了");
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


-(void)getServiceNo:(NSString *)serviceNo{
    NSDateFormatter *sf = [[NSDateFormatter alloc]init];
    [sf setDateFormat:@"yyyy-MM-dd"];
    NSString *startDate = @"2016-01-01";
    NSString *endDate = [sf stringFromDate:[NSDate date]];
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":@"1",@"size":[NSString stringWithFormat:@"%i",20],@"startDate":startDate,@"endDate":endDate,@"query":serviceNo,@"orderType":@"",@"status":@"201,401,301,901,501,601,610,701"};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"order_list_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            NSString *content = data[@"result"];
            
            NSLog(@"%@",content);
            NSArray *array = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (array.count > 0) {
                
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                
                
                OrderDetailViewController *order = [story instantiateViewControllerWithIdentifier:@"order_detail"];
                order.serviceNo = serviceNo;
                [self.navigationController pushViewController:order animated:YES];
            }else{
                [MBProgressHUD showError:@"无该订单信息"];
            }
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}

@end
